package customer

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/google/uuid"
	"go.uber.org/zap"
	"os"
	"server/global"
	commReq "server/model/common/request"
	"server/model/common/response"
	customerReq "server/model/customer/request"
	"server/utils"
	"strings"
)

// AddOrUpdateBug 添加/更新漏洞
func (ca *CustomerApi) AddOrUpdateBug(c *gin.Context) {
	var bug customerReq.CustomerBug
	_ = c.ShouldBindJSON(&bug)

	// 参数校验
	validate := validator.New()
	if err := validate.Struct(&bug); err != nil {
		msg := fmt.Sprintf("请求参数错误,error: %s", err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error("请求参数错误", zap.Error(err))
		return
	}

	if res, action, err := customerService.AddOrUpdateBug(bug); err != nil {
		msg := fmt.Sprintf("%s失败, %s", action, err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error("添加失败", zap.Error(err))
	} else {
		msg := fmt.Sprintf("%s成功", action)
		response.OkWithDetailed(res, msg, c)
	}
}

// GetCustomerBug 获取bug列表
func (ca *CustomerApi) GetCustomerBug(c *gin.Context) {
	var BugSp customerReq.BugSearchParams
	BugSp.Page, _ = utils.StringToInt(c.Query("currentPage"))
	BugSp.PageSize, _ = utils.StringToInt(c.Query("size"))
	BugSp.Name = c.Query("name")
	BugSp.CVE = c.Query("cve")
	BugSp.Tag = c.Query("tag")
	BugSp.Status, _ = utils.StringToUint8(c.Query("status"))
	BugSp.APP, _ = utils.StringToUint8(c.Query("app"))
	BugSp.BugLevel, _ = utils.StringToUint8(c.Query("bugLevel"))

	if list, total, err := customerService.GetBug(BugSp); err != nil {
		response.FailWithMessage("获取失败", c)
		global.TD27_LOG.Error("获取bug列表失败", zap.Error(err))
	} else {
		response.OkWithDetailed(response.PageResult{
			Page:     BugSp.Page,
			PageSize: BugSp.PageSize,
			Total:    total,
			List:     list,
		}, "获取成功", c)
	}
}

// SwitchBugStatus 切换漏洞状态
func (ca *CustomerApi) SwitchBugStatus(c *gin.Context) {
	var bugStatus customerReq.SwitchBugStatus
	_ = c.ShouldBindJSON(&bugStatus)

	// 参数校验
	validate := validator.New()
	if err := validate.Struct(&bugStatus); err != nil {
		msg := fmt.Sprintf("请求参数错误,error: %s", err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error("请求参数错误", zap.Error(err))
		return
	}

	if res, err := customerService.SwitchBugStatus(bugStatus); err != nil {
		msg := fmt.Sprintf("修改状态失败, %s", err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error(msg)
	} else {
		response.OkWithDetailed(res, "修改成功", c)
	}
}

// DeleteBug 删除漏洞
func (ca *CustomerApi) DeleteBug(c *gin.Context) {
	id, _ := utils.StringToInt(c.Param("bugId"))
	var cId commReq.CId
	_ = c.ShouldBindJSON(&cId)

	if err := customerService.DeleteBug(id); err != nil {
		response.FailWithMessage("删除失败", c)
		global.TD27_LOG.Error("删除失败", zap.Error(err))
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// BatchAddBug 批量导入漏洞
func (ca *CustomerApi) BatchAddBug(c *gin.Context) {
	// 获取body中的其他参数
	bugs := customerReq.BatchAddBug{
		Comment: c.PostForm("comment"),
		Tags:    c.PostForm("tags"),
	}
	bugs.CustomerId, _ = utils.StringToUint(c.PostForm("customerID"))
	bugs.EnvVersion, _ = utils.StringToUint(c.PostForm("envVersion"))
	bugs.AttachmentID, _ = utils.StringToUint(c.PostForm("attachmentID"))
	bugs.Feedback, _ = utils.StringToUint(c.PostForm("feedback"))

	// 参数校验
	validate := validator.New()
	if err := validate.Struct(&bugs); err != nil {
		msg := fmt.Sprintf("请求参数错误,error: %s", err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error("请求参数错误", zap.Error(err))
		return
	}

	// 获取要导入的文件
	file, err := c.FormFile("file")
	if err != nil {
		msg := fmt.Sprintf("从表单中获取文件失败，error: %s", err)
		global.TD27_LOG.Error(msg)
		response.FailWithMessage(msg, c)
		return
	}

	// 读取文件内容
	fileBytes, err := utils.FileToBytes(file)
	if err != nil {
		msg := fmt.Sprintf("读取文件内容失败，error: %s", err)
		global.TD27_LOG.Error(msg)
		response.FailWithMessage(msg, c)
		return
	}

	// 生成保存的文件路径
	guid := strings.ReplaceAll(uuid.New().String(), "-", "")
	fileName := guid + "-" + file.Filename
	filePath := "./" + fileName

	// 保存到磁盘
	err = os.WriteFile(filePath, fileBytes, 0644)
	if err != nil {
		msg := fmt.Sprintf("保存文件 %s 失败，error: %s", fileName, err)
		global.TD27_LOG.Error(msg)
		return
	}
	// 执行完后要删除导入的文件
	defer os.Remove(filePath)

	global.TD27_LOG.Info(fmt.Sprintf("文件: %s 保存至%s成功。", fileName, filePath))
	if res, err := customerService.BatchAddBug(bugs, filePath); err != nil {
		msg := fmt.Sprintf("批量导入失败, %s", err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error("批量导入失败", zap.Error(err))
	} else {
		response.OkWithDetailed(res, "批量导入完成", c)
	}
}

// BatchDeleteBug 批量删除漏洞
func (ca *CustomerApi) BatchDeleteBug(c *gin.Context) {
	var ids customerReq.BatchDeleteBug
	_ = c.ShouldBindJSON(&ids)

	// 参数校验
	validate := validator.New()
	if err := validate.Struct(&ids); err != nil {
		msg := fmt.Sprintf("请求参数错误,error: %s", err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error("请求参数错误", zap.Error(err))
		return
	}

	if err := customerService.BatchDeleteBug(ids); err != nil {
		msg := fmt.Sprintf("删除失败, %s", err)
		response.FailWithMessage(msg, c)
		global.TD27_LOG.Error(msg)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}
